package com.jiuli_travel.goods_service.job.timer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jiuli_travel.goods_service.model.entity.Goods;
import com.jiuli_travel.goods_service.model.es.GoodsEsDTO;
import com.jiuli_travel.goods_service.service.IGoodsService;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class ExportGoodsDataToEsTask {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private IGoodsService goodsService;

//    @Scheduled(initialDelay = 60*1000, fixedRate = 60*1000) // 一分钟执行一次
    public void executeTask() throws IOException {
        // 1. 查询所有在这两分钟内更新的goods数据
        Date twoMinutesAgo = DateUtils.addSeconds(new Date(), -120); // 获取当前时间前2分钟的时刻
        List<Goods> goodsList = goodsService.lambdaQuery()
                .ge(Goods::getUpdateTime, twoMinutesAgo)
                .list();

        // 2. 转化数据格式
        List<GoodsEsDTO> goodsEsDTOS = BeanUtil.copyToList(goodsList, GoodsEsDTO.class);

        // 3. 导入到es中
        // 3.1 准备请求
        BulkRequest bulkRequest = new BulkRequest();
        // 3.2 准备DSL
        goodsEsDTOS
                .forEach(goodsEsDTO -> {
                    IndexRequest indexRequest = new IndexRequest("goods_es").id(goodsEsDTO.getId().toString());
                    indexRequest.source(JSONUtil.toJsonStr(goodsEsDTO), XContentType.JSON);
                    bulkRequest.add(indexRequest);
                });
        // 3.3 发起请求
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println(bulkResponse);
    }
}
